package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.mapper.TbOrderRecordMapper;
import com.bwie.mapper.TbProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbOrderDetail;
import com.bwie.pojo.TbOrderRecord;
import com.bwie.pojo.TbProdInfo;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author 牛y
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-07-23 17:04:43
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @Autowired
    TbProdInfoMapper tbProdInfoMapper;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    TbOrderRecordMapper tbOrderRecordMapper;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {
        String token = request.getHeader("token");
        if(token==null){
            return R.ERROR(500,"用户请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())){
            wrapper.lambda().like(TbOrder::getProdInfo,pageInfoVo.getKeyWord())
                    .or().eq(TbOrder::getOrderId,pageInfoVo.getKeyWord());
        }
        if(pageInfoVo.getTypeId()!=null){
            wrapper.lambda().eq(TbOrder::getOrderType,pageInfoVo.getTypeId());
        }
        if(pageInfoVo
                .getStatusId()!=null){
            wrapper.lambda().eq(TbOrder::getOrderStatus,pageInfoVo.getStatusId());
        }
        wrapper.lambda().orderByDesc(TbOrder::getOrderId);
        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page, wrapper);
        for (TbOrder record : tbOrderPage.getRecords()) {
            List<String> imageList=tbOrderMapper.selectImageList(record.getOrderId());
            ArrayList<String> image = new ArrayList<String>();
            if(imageList.size()>0 && imageList!=null){
                for (String s : imageList) {
                    if(s!=null){
                        image.add(s);
                    }
                }
            }
            record.setImageList(image);
        }
        String key="order-list"+userId;
        redisTemplate.opsForValue().set(key,JSON.toJSONString(tbOrderPage.getRecords()));
        return R.OK(tbOrderPage);
    }

    @Override
    public R deleteBatchByOrder(List<TbOrder> orderList) {
        for (TbOrder tbOrder : orderList) {
            tbOrderMapper.deleteById(tbOrder.getOrderId());
        }
        return R.OK();
    }

    @Override
    public void uploadExout(Integer userId) {
        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<>(TbOrder.class);
        String key="order-list"+userId;
        String redisOrder = redisTemplate.opsForValue().get(key);
        excelUtil.exportExcel(response,JSON.parseArray(redisOrder,TbOrder.class),"订单信息");
    }

    @Override
    public R getProdInfo() {
        List<TbProdInfo> tbProdInfos = tbProdInfoMapper.selectList(null);
        return R.OK(tbProdInfos);
    }

    @Override
    public R addOrder(List<TbProdInfo> infoList) {
        BigDecimal bigDecimalAmount = new BigDecimal("0");
        StringBuilder prodNames = new StringBuilder();
        String token = request.getHeader("token");
        if(token==null){
            return R.ERROR(500,"用户请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String userName = body.get("userName", String.class);
        RLock lock = redissonClient.getLock("order-lock");
        try {
            lock.lock();
            //检查库存 扣减库存
            for (TbProdInfo tbProdInfo : infoList) {
                TbProdInfo prodInfo = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
                if(tbProdInfo.getBuyNum()>prodInfo.getProdStock()){
                    throw new RuntimeException("库存不足");
                }
                prodInfo.setProdStock(prodInfo.getProdStock()-tbProdInfo.getBuyNum());
                //计算金额
                bigDecimalAmount=bigDecimalAmount.add(tbProdInfo.getProdPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())));
                if(prodNames.length()>0){
                    prodNames.append(",").append(tbProdInfo.getProdName());
                }else {
                    prodNames.append(tbProdInfo.getProdName());
                }
            }
        }
        finally {
            lock.unlock();
        }


        TbOrder tbOrder = new TbOrder();
        long id = IdUtil.getSnowflake(1, 1).nextId();
        tbOrder.setOrderNo(id+"");
        tbOrder.setOrderAmount(bigDecimalAmount);
        tbOrder.setOrderStatus(0);
        tbOrder.setOrderType(1);
        tbOrder.setCreateBy(userName);
        tbOrder.setCreateTime(new Date());
        tbOrder.setProdInfo(prodNames.toString());
        tbOrder.setUserId(userId);
        tbOrderMapper.insert(tbOrder);

        for (TbProdInfo prodInfo : infoList) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();
            tbOrderDetail.setOrderId(tbOrder.getOrderId());
            tbOrderDetail.setBuyNum(prodInfo.getBuyNum());
            tbOrderDetail.setCreateBy(userName);
            tbOrderDetail.setCreateTime(new Date());
            tbOrderDetail.setBuyPrice(prodInfo.getProdPrice());
            tbOrderDetail.setInfoId(prodInfo.getInfoId());
            tbOrderDetail.setProdId(prodInfo.getProdId());
            tbOrderDetailMapper.insert(tbOrderDetail);
        }

        TbOrderRecord tbOrderRecord = new TbOrderRecord();
        tbOrderRecord.setOrderId(tbOrder.getOrderId());
        tbOrderRecord.setCreateBy(userName);
        tbOrderRecord.setCreateTime(new Date());
        tbOrderRecord.setOptRecord("用户创建订单");
        tbOrderRecordMapper.insert(tbOrderRecord);

        return R.OK();
    }
}




